package com.jx.mlxg.mapper;

import com.jx.mlxg.entity.Addresses;
import com.jx.mlxg.entity.Orders;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.jx.mlxg.entity.Product;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
* @author Administrator
* @description 针对表【orders】的数据库操作Mapper
* @createDate 2025-02-25 21:15:46
* @Entity entity.entity.Orders
*/
@Mapper
public interface OrdersMapper extends BaseMapper<Orders> {
    /**
     * 根据订单ID查询地址信息
     * @param orderId 订单ID
     * @return 地址信息
     */
    @Select("SELECT a.* FROM addresses a JOIN orders o ON a.address_id = o.address_id WHERE o.order_id = #{orderId}")
    Addresses selectAddressByOrderId(@Param("orderId") String orderId);

    /**
     * 根据订单ID查询产品信息
     * @param orderId 订单ID
     * @return 产品列表
     */
//    @Select("SELECT p.* FROM product p " +
//            "JOIN order_details od ON p.product_id = od.product_id " +
//            "JOIN orders o ON od.order_id = o.order_id " +
//            "WHERE o.order_id = #{orderId}")
    @Select("SELECT p.*, od.quantity FROM product p " +
            "JOIN order_details od ON p.product_id = od.product_id " +
            "JOIN orders o ON od.order_id = o.order_id " +
            "WHERE o.order_id = #{orderId}")
    List<Product> selectProductsByOrderId(@Param("orderId") String orderId);

    /**
     * 根据用户ID查询订单统计信息
     */
    List<Map<String, Object>> getOrderStatisticsByUserId(@Param("userId") int userId);

    /**
     * 根据用户ID查询总购买数量
     */
    int getTotalBoughtCountByUserId(@Param("userId") int userId);

    @Select("SELECT * FROM orders WHERE out_trade_no = #{outTradeNo}")
    Orders selectByOutTradeNo(@Param("outTradeNo") String outTradeNo);

    @Update("UPDATE orders SET transaction_id = #{transactionId}, status = #{status} WHERE out_trade_no = #{outTradeNo}")
    int updateOrderStatus(@Param("outTradeNo") String outTradeNo, @Param("transactionId") String transactionId, @Param("status") String status);

    Orders selectByOrderId(@Param("orderId")String orderId);

    Addresses selectAddressByAddressId(@Param("addressId") Integer addressId);

    /**
     * 查询订单总金额
     * @param timeRange 时间范围条件（可为null表示查询所有时间）
     * @return 订单总金额
     */
    @Select({"SELECT SUM(real_amount) FROM orders",
            "WHERE 1=1 ${timeRange}"})
    BigDecimal selectSumTotalAmount(@Param("timeRange") String timeRange);
}




